/*
 * Copyright (c) 2015 LingoChamp Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.liulishuo.filedownloader.services;

import com.liulishuo.filedownloader.PauseAllMarker;
import com.liulishuo.filedownloader.download.CustomComponentHolder;
import com.liulishuo.filedownloader.i.IFileDownloadIPCService;
import com.liulishuo.filedownloader.util.ExtraKeys;
import com.liulishuo.filedownloader.util.FileDownloadHelper;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.liulishuo.filedownloader.util.FileDownloadProperties;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationSlot;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.lang.ref.WeakReference;

/**
 * The service is running for FileDownloader.
 * <p/>
 * You can add a command `process.non-separate=true` to the `filedownloader.properties` asset file
 * to make the FileDownloadService runs in the main process, and by default the FileDownloadService
 * runs in the separate process(`:filedownloader`).
 */
public class FileDownloadService extends Ability {
    //public final String TAG = FileDownloadService.class.getSimpleName();
    public final String TAG = "Service";
    private IFileDownloadServiceHandler handler;
    private PauseAllMarker pauseAllMarker;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        FileDownloadHelper.holdContext(this);
        try {
            FileDownloadUtils.setMinProgressStep(
                    FileDownloadProperties.getImpl().downloadMinProgressStep);
            FileDownloadUtils.setMinProgressTime(
                    FileDownloadProperties.getImpl().downloadMinProgressTime);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        final FileDownloadManager manager = new FileDownloadManager();

        if (FileDownloadProperties.getImpl().processNonSeparate) {
            handler = new FDServiceSharedHandler(new WeakReference<>(this), manager);
        } else {
            handler = new FDServiceSeparateHandler(new WeakReference<>(this), manager);
        }

        PauseAllMarker.clearMarker();
        pauseAllMarker = new PauseAllMarker((IFileDownloadIPCService) handler);
        pauseAllMarker.startPauseAllLooperCheck();
    }

    @Override
    protected void onCommand(Intent intent, boolean restart, int startId) {
        super.onCommand(intent, restart, startId);

        handler.onStartCommand(intent, 0, startId);
        inspectRunServiceForeground(intent);
    }

    private void inspectRunServiceForeground(Intent intent) {

        if (intent == null) return;
        final boolean isForeground = intent.getBooleanParam(ExtraKeys.IS_FOREGROUND, false);
        if (isForeground) {
            ForegroundServiceConfig config = CustomComponentHolder.getImpl()
                    .getForegroundConfigInstance();
            if (config.isNeedRecreateChannelId()) {
                NotificationSlot notificationSlot = new NotificationSlot(
                        config.getNotificationChannelId(),
                        config.getNotificationChannelName(),
                        NotificationSlot.LEVEL_LOW
                );
                try {
                    NotificationHelper.addNotificationSlot(notificationSlot);
                    keepBackgroundRunning(config.getNotificationId(),config.getNotification(this));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            keepBackgroundRunning(config.getNotificationId(),config.getNotification(this));
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(this, "run service foreground with config: %s", config);
            }
        }
    }
    @Override
    protected void onStop() {

        pauseAllMarker.stopPauseAllLooperCheck();
        cancelBackgroundRunning();
        super.onStop();
    }
    @Override
    protected IRemoteObject onConnect(Intent intent) {

        return handler.onBind(intent);
    }

    @Override
    protected void onDisconnect(Intent intent) {

        super.onDisconnect(intent);
    }
}
